<template>
    <div class="databaseDb-success-container">

        <!-- 搜索框 -->
        <div class="filter-container" style>
            <!-- large, medium, small, mini -->
            <el-input
            clearable
            size="medium"
            v-model="listQuery.search"
            :placeholder="typeName"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="fetchData"
            >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>

            <el-input
            v-if="listQuery.sqlType == 6"
            clearable
            size="medium"
            v-model="listQuery.search1"
            placeholder="服务名称"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="fetchData"
            >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>

            <!-- 流程状态 -->
            <el-select
            v-if="listQuery.sqlType == 5"
            size="medium" v-model="listQuery.status" placeholder="流程状态" clearable class="filter-item" style="width: 130px">
                <el-option v-for="item in typeOptions" :key="item.key" :label="item.display_name" :value="item.display_name" />
            </el-select>

            <!-- <el-date-picker
            class="filter-item"
            size="medium"
            v-model="time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
            </el-date-picker> -->

            <el-date-picker
            class="filter-item"
            size="medium"
            v-model="time[0]"
            type="datetime"
            placeholder="开始时间"
            :picker-options="pickerOptions0"
            >
            </el-date-picker>

            <el-date-picker
            class="filter-item"
            size="medium"
            v-model="time[1]"
            type="datetime"
            placeholder="结束时间"
            :picker-options="pickerOptions1"
            >
            </el-date-picker>
            
            <el-button
                v-waves
                class="filter-item"
                type="primary"
                size="medium"
                icon="el-icon-search"
                @click="fetchData"
                style="margin-right: 50px;"
            >搜索</el-button>

            <!-- 类型选择 -->
            <div class="filter-item" style="display: inline-block;">
                <el-radio-group v-model="listQuery.sqlType" size="mini" @change="changeType">

                    <template v-for="item in radioList">
                        <el-radio-button :label="item.value" :key="item.value">{{item.label}}</el-radio-button>
                    </template>

                </el-radio-group>
            </div>

        </div>

        <!-- 表格 -->
        <!-- :header-cell-style="{background:'#f1f1f1'}" -->
        <el-table
            :key="key"
            :show-header="true"
            height="250"
            v-loading="listLoading"
            :data="list"
            fit
            highlight-current-row
            style="width: 100%;flex-grow: 1;overflow: auto;"
            @current-change="handleCurrentChange"
        >

            <el-table-column align="center" label="ID" width="80">
                <template slot-scope="scope">{{ scope.$index+1 }}</template>
            </el-table-column>

            <!-- 流程名称 流程状态	流程启动时间 流程结束时间 运行时间 -->
            <el-table-column 
            v-for="thead in formThead" 
            :width="thead.width"
            align="center"
            :key="thead.id" 
            :label="thead.label"
            :prop="thead.name"
            :formatter="(row, column, cellValue, index) => { return formatterColumn(row, column, cellValue, index, thead) }"
            >
                <!-- 如果使用template formatter 失效 -->
                <!-- <template slot-scope="scope">
                    {{ scope.row[thead.name] }}
                </template> -->
            </el-table-column>

            <el-table-column width="120px" align="center" label="操作">
                <template slot-scope="scope">
                    <el-button
                    size="mini"
                    type="primary" 
                    plain
                    @click="showDetail(scope.row)">详情</el-button>
                </template>
            </el-table-column>
            
        </el-table>

        <!-- 详情 -->
        <el-dialog title="详情" :visible.sync="dialogFormVisible">
            <el-form :model="form" label-position="left">

                <el-row :gutter="20">

                    <el-col
                    v-for="thead in formThead"
                    :key="thead.id" 
                    :span="24">
                        <div class="grid-content bg-purple">
                            <el-form-item :label="thead.label+':'" >
                                {{ formatterColumn2(form, thead) }}
                            </el-form-item>
                        </div>
                    </el-col>
                    
                </el-row>
                
            </el-form>
            <!-- <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
            </div> -->
        </el-dialog>

        <!-- 分页 -->
        <pagination
            v-show="total>=0"
            :total="total"
            :page.sync="listQuery.pageNum"
            :limit.sync="listQuery.pageSize"
            @pagination="fetchData"
        />
    </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
// import { mapGetters } from 'vuex'
import waves from "@/directive/waves/index.js"; // 水波纹指令
// import elDragDialog from '@/directive/el-drag-dialog' //拖动 base on element-ui
import { getList, getDbLogList } from "@/api/windows";
import { formatStrTime, parseTime } from '@/utils/dateUtil+8h'

const typeOptions = [
  { key: '1', display_name: 'Started' },
  { key: '2', display_name: 'Completed' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const typeKeyValue = typeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

const formTheadBK = {
    5: [
        {id: 1, type: '', width: '', label: '流程名称', name: 'Service/Name'},
        {id: 2, type: '', width: '120px', label: '流程状态', name: 'ServiceInstance/State'},
        {id: 3, type: 'date', width: '160px', label: '流程启动时间', name: 'ServiceInstance/StartTime'},
        {id: 4, type: 'date', width: '160px', label: '流程结束时间', name: 'ServiceInstance/EndTime'},
        {id: 5, type: '', width: '160px', label: '运行时间', name: 'ServiceInstance/Duration'}
        ],
    6: [
        {id: 1, type: '', width: '160px', label: '端口名称',name: 'Port Name'},
        {id: 2, type: '', width: '120px', label: '流向',name: 'Event Type'},
        {id: 3, type: '', width: '', label: '服务名称',name: 'Service Name'},
        {id: 4, type: '', width: '120px', label: '适配器',name: 'Adapter'},
        {id: 5, type: '', width: '', label: '调用地址',name: 'URI'},
        {id: 6, type: 'date', width: '160px', label: '调用时间',name: 'Timestamp'},
        {id: 7, type: '', width: '120px', label: '数据大小（b）',name: 'Size'}
        ]
};


export default {
    name: "DbSuccess",
    components: {
        Pagination
    },
    directives: {
        waves
        // elDragDialog// 拖动
    },
    filters: {
        formatStrTime,
        parseTime,
        statusFilter(status) {
            const statusMap = {
                0: "info",
                1: "danger",
                2: "success"
            };
            return statusMap[status];
        }
    },
    // computed: {
    //   ...mapGetters([
    //     'name',
    //     "locations"
    //   ])
    // },
    computed: {
        typeName: vm => {
            return vm.placeholders[vm.listQuery.sqlType].label;
        }
    },
    data() {
        return {
            pickerOptions0: {
                disabledDate: (curtime) => {
                    let this_ = this;
                    if(this_.time[1]){
                        return curtime.getTime() > new Date(this_.time[1])
                    }
                    return false
                }
            },
            pickerOptions1: {
                disabledDate: (curtime) => {
                    let this_ = this;
                    if(this_.time[0]){
                        return curtime.getTime() < new Date(this_.time[0]) - 24 * 60 * 60 * 1000 + 1000
                    }
                    return false
                }
            },
            typeOptions,
            list: null,
            // 数据总条数
            total: 0,
            listLoading: true,
            // 分页信息
            listQuery: {
                pageNum: 1,
                pageSize: 10,
                importance: undefined,
                title: undefined,
                type: undefined,
                sort: "+id",
                location: "",
                dbType: '1',
                sqlType: '5',
                search: '',
                search1: '',
                status: '',
                startTime: '',
                endTime: ''
            },
            time: [],
            dialogTableVisible: false,
            dialogFormVisible: false,
            currentRow: null,
            // sqlType: '1',
            placeholders: {
                5: {
                    label:'流程名称',
                    value:'5'
                },
                6: {
                    label:'端口名称',
                    value:'6'
                }
            },
            radioList: [
                {
                    label:'所有成功调用流程清单',
                    value:'5'
                },{
                    label:'所有成功传入传出信息列表',
                    value:'6'
                }
            ],
            key: 1, // table key
            formThead: formTheadBK[5],
            // ******************************** 详情弹窗S ********************************
            dialogFormVisible: false,
            form: {
                ApplicationName: '',
                SendPort: '',
                Type: '',
                dtCreated: '',
                dtSuspendTimeStamp: '',
                nvcErrorDescription: '',
                nvcErrorID: '',
                uidInstanceID: ''
            },
            formLabelWidth: '120px'
            // ******************************** 详情弹窗E ********************************
        };
    },
    watch: {
        'listQuery.sqlType'(val, oldVal) {
            this.formThead = formTheadBK[val];
            this.key = this.key + 1// 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
        }
    },
    created() {
        this.listQuery.dbType = this.$route.meta.dbType;// 数据库选择
        // console.log("TCL: created -> this.$route.meta.dbType", this.$route.meta.dbType)
        this.fetchData();
        // this.listLoading = false;
    },
    methods: {
        
        // 弹窗用
        formatterColumn2(row, thead){
            let cellValue = row[thead.name];
            if(thead.type == 'date' && cellValue){// 格式化日期
                let strTime = formatStrTime(cellValue, 'yyyy-MM-dd hh:mm:ss')
                return strTime;
            }else{
                return cellValue;
            }
        },

        /**
         * 用来格式化内容
         */
        formatterColumn(row, column, cellValue, index, thead){
            // debugger;
            if(thead.type == 'date' && cellValue){// 格式化日期
                let strTime = formatStrTime(cellValue, 'yyyy-MM-dd hh:mm:ss')
                return strTime;
            }else{
                return cellValue;
            }
        },
        /**
         * 请求后台数据
         */
        fetchData() {
            // return;
            this.listLoading = true;
            if(this.time != null && this.time.length > 0){
                this.listQuery.startTime = this.time[0];
                this.listQuery.endTime = this.time[1];
            }else{
                this.listQuery.startTime = '';
                this.listQuery.endTime = ''
            }
            // console.log("TCL: fetchData -> this.listQuery", this.listQuery)
            getDbLogList(this.listQuery).then(response => {
            // getList(this.listQuery).then(response => {
                // 分页信息
                let pageInfo = response.data;
                // 总数
                this.total = pageInfo.total;
                // 分页数据
                this.list = pageInfo.list;
                this.listLoading = false;
            });
        },
        /**
         * 当表格的当前行发生变化的时候会触发该事件，如果要高亮当前行，请打开表格的 highlight-current-row 属性
         */
        handleCurrentChange(val) {
            this.currentRow = val;
        },
        /**
         * TAB标签切换event
         */
        changeType(label){
            // debugger;
            this.listQuery.sqlType = label;
            this.fetchData();
        },
        showDetail(row){
            console.log("TCL: showDetail -> row", row)
            this.dialogFormVisible = true;
            this.form = row;
        }
    }
};
</script>

<style lang="scss" scoped>
.databaseDb-success {
    &-container {
        padding: 5px;
        // margin: 30px;
        // background-color: #f0f2f5;
        // height: 100%;
        width: 100%;
        display: flex;
        flex-direction: column;
    }
    &-text {
        font-size: 30px;
        line-height: 46px;
    }
}
.databaseDb-success-container {
    
}
</style>
<style lang="scss">
.databaseDb-success-container {
    
    .btn-show{
        color: #3a8ee6;
    }
    .btn-show:hover{
        color: #3a8ee6c2;
        text-decoration: underline;
    }

    .cls-textarea{
        .el-textarea__inner{
            background-color: #f5f7fa;
            border: none;
        }
    }
    
}
</style>